package hjt.com.module_test.annotation;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by hjt on 2019/4/22.
 */

public class Inject {

    /**
     * 简单的注解使用
     *
     * @param object
     */
    public static void bind(final Object object) {
        //注入
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                //确定注解类型
                if (field.isAnnotationPresent(InjectView.class)) {
                    //允许修改反射属性
                    field.setAccessible(true);
                    InjectView injectView = field.getAnnotation(InjectView.class);
                    //findViewById将注解的id,找到View注入到成员变量中
                    field.set(object, ((Activity) object).findViewById(injectView.value()));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //点击事件
        Method[] declaredMethods = object.getClass().getDeclaredMethods();
        for (final Method method : declaredMethods) {
            try {
                if (method.isAnnotationPresent(InjectClick.class)) {
                    method.setAccessible(true);
                    InjectClick injectClick = method.getAnnotation(InjectClick.class);
                    for (int resId : injectClick.value()) {
                        ((Activity) object).findViewById(resId).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    method.invoke(object, v);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
